from common.base_view import response_json
from common.const import *
from common.jwt_utils import JWT
from common.lib_mysql import News


class User(News):
    def __init__(self):
        super().__init__()
        self.table = "users_users"

    def user_login(self, phone, password):
        sql = """
        select * from users_users where phone = '{}' and password = '{}'
        """.format(phone, password)
        print(sql)
        users = self.exec_sql(sql)
        if len(users):
            user = users[0]
            if user.get("password"):
                del user["password"]
            token = JWT.get_token(user)
            return response_json(CODE_OK, token)
        else:
            return response_json(CODE_LOGIN_FAIL)

    def user_login1(self, phone, password):
        sql = """
        select * from users_users where phone = '{}' and password = '{}'
        """.format(phone, password)
        print(sql)
        users = self.exec_sql(sql)
        if len(users):
            user = users[0]
            if user.get("password"):
                del user["password"]
            token = JWT.get_token(user)
            return response_json(CODE_OK, token)
        else:
            return response_json(CODE_USER_LOGIN_FAIL)

    def list(self, page, search_key, size=15):
        search_sql = """
        where username like "%{}%" or phone like "%{}%" or nickname like "%{}%"
        """.format(search_key, search_key, search_key)

        info_sql = """
        select id, username, phone, email, photo, nickname, country, city, region, address, age, gender, user_type, created, updated
        from users_users {}  order by updated desc limit {} OFFSET {}
        """

        total_sql = """
        select count(*) as total
        from users_users {}
        """
        if page <= 0:
            page = 1
        if search_key == "" or not search_key:
            info_sql = info_sql.format("", size, (page - 1) * size)
            total_sql = total_sql.format("")
        else:
            info_sql = info_sql.format(search_sql, size, (page - 1) * size)
            total_sql = total_sql.format(search_sql)

        users = self.exec_sql(info_sql)
        total = self.find_one(total_sql)
        print(info_sql, total_sql)
        return response_json(CODE_OK, {"total": total.get("total"), "users": users})

    def delete(self, ids):
        return self.delete_func(self.table, ids)

    def insert(self, insert_dict):
        return self.insert_func(self.table, insert_dict, True)

    def update(self, id, up_dict):
        return self.update_by_id_func(self.table, [id], up_dict)